
import os, cgi, random, logging, wsgiref.handlers
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from models import *


class MainPage(webapp.RequestHandler):
  def get(self):
    questions = []
    answers = []
    answer = None

    q_param = self.request.get('q')
    a_param = self.request.get('a')
    t_param = self.request.get('t')

    topics = Topic.all()
    q_query = []
    if len(t_param) == 0:
      q_query = Question.all()
    else:
      topic = Topic.get(t_param)
      logging.info('Filtering by topic'+topic.text)
      logging.info('Topic has '+str(len(topic.questions))+' questions.')
      if len(topic.questions) > 0:
        q_query = Question.get(topic.questions)
      else:
        q_query = Question.all()

    if len(q_param) == 0:
      for q in q_query:
        questions.append(q)
      question = random.choice(questions)
    else:
      question = Question.get(q_param)
      questions = q_query
    if len(a_param) == 0:
      for a in question.answer_set:
        answers.append(a)
      if len(answers) > 0:
        answer = random.choice(answers)
        if answer.rating is None:
          answer.rating = 0
          answer.put()
    else:
      answer = Answer.get(a_param)

    question_topics = []
    for topic_key in question.topics:
      question_topics.append(Topic.get(topic_key).text)

    context = { 'topics' : topics, 'questions' : questions,
                'question' : question, 'answer' : answer,
                'question_topics' : question_topics,
              }
    view = 'index.html'
    render(self.response,view,context)


class QuestionController(webapp.RequestHandler):
  def post(self):
    question = Question()
    question.text = cgi.escape(self.request.get('question_text'))
    q_topics = self.request.get('question_topics').rsplit()
    topics = []
    for t in q_topics:
      results = Topic.gql('WHERE text = :1',t.lower()).fetch(1)
      if len(results) > 0:
        for r in results:
          topics.append(r.key())
      else:
        topic = Topic()
        topic.text = t
        topic.put()
        topics.append(topic.key())
    logging.info( "TOPICS: "+ str(topics) )
    question.topics = topics
    question.put()
    for topic in Topic.get(question.topics):
      topic.questions.append(question.key())
      topic.put()
    self.redirect('/')

class QuestionAndAnswerController(webapp.RequestHandler):
  def post(self,key):
    question = Question.get(key)
    answer = Answer()
    answer.question = question
    answer.text =  cgi.escape(self.request.get('answer_text'))
    answer.rating = 0
    answer.put()
    self.redirect('/')

class AnswerController(webapp.RequestHandler):
  def post(self,key):
    answer = Answer.get(key)
    answer.rating += int(self.request.get('vote'))
    answer.put()
    question_key = self.request.get('question_key')
    self.redirect('/?q='+question_key+'&a='+key)


def render(response,view,context):
  path = os.path.join(os.path.dirname(__file__), 'templates/'+view)
  response.out.write(template.render(path,context))
